﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'menstrual_cycle_setup_logic.dart';

/// 生理周期设置页面
class MenstrualCycleSetupView extends GetView<MenstrualCycleSetupLogic> {
  const MenstrualCycleSetupView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(24.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 返回按钮
              GestureDetector(
                onTap: () => Get.back(),
                child: Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    color: Colors.grey[800],
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.white,
                    size: 20.sp,
                  ),
                ),
              ),
              
              SizedBox(height: 40.h),
              
              // 标题
              Text(
                '生理周期设置',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              
              SizedBox(height: 40.h),
              
              // 设置项
              _buildSettingItem(
                title: '生理期天数',
                subtitle: '您的生理期通常持续几天？',
                value: controller.state.periodDays,
                onTap: () => _showPeriodDaysSelector(),
              ),
              
              SizedBox(height: 24.h),
              
              _buildSettingItem(
                title: '周期天数',
                subtitle: '您的生理期间隔是多少天？',
                value: controller.state.cycleDays,
                onTap: () => _showCycleDaysSelector(),
              ),
              
              SizedBox(height: 24.h),
              
              _buildSettingItem(
                title: '上次生理期开始日期',
                subtitle: '您上次生理期是什么时候开始的',
                value: controller.state.lastPeriodDate,
                onTap: () => _showDatePicker(),
                isDate: true,
              ),
              
              const Spacer(),
              
              // 底部按钮
              Row(
                children: [
                  Expanded(
                    child: Container(
                      height: 56.h,
                      child: TextButton(
                        onPressed: () => Get.back(),
                        style: TextButton.styleFrom(
                          backgroundColor: Colors.transparent,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(28.r),
                            side: BorderSide(color: Colors.grey[600] ?? Colors.grey),
                          ),
                        ),
                        child: Text(
                          '取消',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  
                  SizedBox(width: 16.w),
                  
                  Expanded(
                    child: Obx(() {
                      final isComplete = controller.isSetupComplete();
                      return Container(
                        height: 56.h,
                        child: ElevatedButton(
                          onPressed: isComplete ? () async {
                              await controller.completeSetup();
                          } : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: isComplete 
                                ? const Color(0xFFFF6B35) 
                                : Colors.grey[700],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(28.r),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            isComplete ? '完成' : '下一步',
                            style: TextStyle(
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      );
                    }),
                  ),
                ],
              ),
              
              SizedBox(height: 24.h),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建设置项
  Widget _buildSettingItem({
    required String title,
    required String subtitle,
    required RxString value,
    required VoidCallback onTap,
    bool isDate = false,
  }) {
    return Obx(() {
      final hasValue = value.value.isNotEmpty && value.value != '请选择';
      
      return GestureDetector(
        onTap: onTap,
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(
              color: hasValue ? const Color(0xFFFF6B35) : (Colors.grey[700] ?? Colors.grey),
              width: 1.5,
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                    
                    SizedBox(height: 8.h),
                    
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                ),
              ),
              
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    hasValue ? value.value : '请选择',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: hasValue ? const Color(0xFFFF6B35) : Colors.grey[500],
                    ),
                  ),
                  
                  SizedBox(height: 8.h),
                  
                  Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.grey[500],
                    size: 16.sp,
                  ),
                ],
              ),
            ],
          ),
        ),
      );
    });
  }

  /// 显示生理期天数选择器
  void _showPeriodDaysSelector() {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.grey[900],
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (context) => _buildDaySelector(
        title: '生理期天数',
        values: List.generate(8, (index) => (index + 4).toString()),
        selectedValue: controller.state.periodDays,
        onConfirm: (value) {
          controller.state.periodDays.value = '$value天';
          Get.back();
        },
      ),
    );
  }

  /// 显示周期天数选择器
  void _showCycleDaysSelector() {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.grey[900],
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (context) => _buildDaySelector(
        title: '周期天数',
        values: List.generate(8, (index) => (index + 26).toString()),
        selectedValue: controller.state.cycleDays,
        onConfirm: (value) {
          controller.state.cycleDays.value = '$value天';
          Get.back();
        },
      ),
    );
  }

  /// 显示日期选择器
  void _showDatePicker() {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.grey[900],
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (context) => _buildDateSelector(),
    );
  }

  /// 构建天数选择器
  Widget _buildDaySelector({
    required String title,
    required List<String> values,
    required RxString selectedValue,
    required Function(String) onConfirm,
  }) {
    final currentSelected = values.first.obs;
    
    return Container(
      height: 400.h,
      padding: EdgeInsets.all(24.w),
      child: Column(
        children: [
          // 头部
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(
                onPressed: () => Get.back(),
                child: Text(
                  '取消',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.grey[400],
                  ),
                ),
              ),
              
              Text(
                title,
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              
              TextButton(
                onPressed: () => onConfirm(currentSelected.value),
                child: Text(
                  '完成',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFFFF6B35),
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          
          SizedBox(height: 20.h),
          
          // 选择器
          Expanded(
            child: ListView.builder(
              itemCount: values.length,
              itemBuilder: (context, index) {
                final value = values[index];
                return Obx(() {
                  final isSelected = currentSelected.value == value;
                  
                  return GestureDetector(
                    onTap: () => currentSelected.value = value,
                    child: Container(
                      height: 60.h,
                      margin: EdgeInsets.symmetric(vertical: 4.h),
                      decoration: BoxDecoration(
                        color: isSelected ? const Color(0xFFFF6B35).withOpacity(0.2) : Colors.transparent,
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Center(
                        child: Text(
                          '$value 天',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                            color: isSelected ? const Color(0xFFFF6B35) : Colors.white,
                          ),
                        ),
                      ),
                    ),
                  );
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建日期选择器
  Widget _buildDateSelector() {
    final currentDate = DateTime.now().obs;
    
    return Container(
      height: 500.h,
      padding: EdgeInsets.all(24.w),
      child: Column(
        children: [
          // 头部
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(
                onPressed: () => Get.back(),
                child: Text(
                  '取消',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.grey[400],
                  ),
                ),
              ),
              
              Text(
                '上次生理期开始日期',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              
              TextButton(
                onPressed: () {
                  final date = currentDate.value;
                  controller.state.lastPeriodDate.value = '${date.year}年${date.month}月${date.day}日';
                  Get.back();
                },
                child: Text(
                  '完成',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFFFF6B35),
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          
          SizedBox(height: 20.h),
          
          // 日期选择器
          Expanded(
            child: _buildCustomDatePicker(currentDate),
          ),
        ],
      ),
    );
  }

  /// 构建自定义日期选择器
  Widget _buildCustomDatePicker(Rx<DateTime> currentDate) {
    final years = List.generate(5, (index) => DateTime.now().year - index);
    final months = List.generate(12, (index) => index + 1);
    final days = List.generate(31, (index) => index + 1);
    
    return Row(
      children: [
        // 年份选择
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Text(
                    '年',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: years.length,
                    itemBuilder: (context, index) {
                      final year = years[index];
                      return Obx(() {
                        final isSelected = currentDate.value.year == year;
                        
                        return GestureDetector(
                          onTap: () {
                            currentDate.value = DateTime(
                              year,
                              currentDate.value.month,
                              currentDate.value.day,
                            );
                          },
                          child: Container(
                            height: 50.h,
                            decoration: BoxDecoration(
                              color: isSelected ? const Color(0xFFFF6B35).withOpacity(0.3) : Colors.transparent,
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            child: Center(
                              child: Text(
                                '$year年',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: isSelected ? const Color(0xFFFF6B35) : Colors.white,
                                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                ),
                              ),
                            ),
                          ),
                        );
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        
        SizedBox(width: 12.w),
        
        // 月份选择
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Text(
                    '月',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: months.length,
                    itemBuilder: (context, index) {
                      final month = months[index];
                      return Obx(() {
                        final isSelected = currentDate.value.month == month;
                        
                        return GestureDetector(
                          onTap: () {
                            currentDate.value = DateTime(
                              currentDate.value.year,
                              month,
                              currentDate.value.day,
                            );
                          },
                          child: Container(
                            height: 50.h,
                            decoration: BoxDecoration(
                              color: isSelected ? const Color(0xFFFF6B35).withOpacity(0.3) : Colors.transparent,
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            child: Center(
                              child: Text(
                                '$month月',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: isSelected ? const Color(0xFFFF6B35) : Colors.white,
                                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                ),
                              ),
                            ),
                          ),
                        );
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        
        SizedBox(width: 12.w),
        
        // 日期选择
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Text(
                    '日',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: days.length,
                    itemBuilder: (context, index) {
                      final day = days[index];
                      return Obx(() {
                        final isSelected = currentDate.value.day == day;
                        
                        return GestureDetector(
                          onTap: () {
                            currentDate.value = DateTime(
                              currentDate.value.year,
                              currentDate.value.month,
                              day,
                            );
                          },
                          child: Container(
                            height: 50.h,
                            decoration: BoxDecoration(
                              color: isSelected ? const Color(0xFFFF6B35).withOpacity(0.3) : Colors.transparent,
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            child: Center(
                              child: Text(
                                '$day日',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: isSelected ? const Color(0xFFFF6B35) : Colors.white,
                                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                ),
                              ),
                            ),
                          ),
                        );
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
